package org.example.domain.order.domainservice.impl;

import com.alibaba.cola.exception.Assert;
import org.example.client.context.UserContext;
import org.example.domain.item.entity.ItemEntity;
import org.example.domain.item.gateway.ItemGateway;
import org.example.domain.order.domainservice.OrderCreateDomainService;
import org.example.domain.order.entity.OrderEntity;
import org.example.domain.order.entity.OrderItemEntity;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class OrderCreateDomainServiceImpl implements OrderCreateDomainService {

    @Resource
    private ItemGateway itemGateway;

    @Override
    public void process(OrderEntity orderEntity) {
        // 校验订单金额
        orderEntity.validatePayAmount();
        // 校验订单商品列表
        validateOrderItemList(orderEntity.getOrderItemList());
        // 生成订单号
        orderEntity.generateOrderNo();
        // 从 ThreadLocal 中获取用户ID
        orderEntity.setUserId(UserContext.getUserId());
        // 将订单号组装到订单商品中
        orderEntity.setOrderItemListOrderNo();
    }

    /**
     * 校验订单商品列表
     * @param orderItemEntityList 订单商品列表
     */
    private void validateOrderItemList(List<OrderItemEntity> orderItemEntityList) {
        Set<Long> itemIdSet = orderItemEntityList.stream().map(OrderItemEntity::getItemId).collect(Collectors.toSet());
        List<ItemEntity> itemEntityList = itemGateway.loadByIds(itemIdSet);
        Map<Long, ItemEntity> itemMap = itemEntityList.stream().collect(Collectors.toMap(ItemEntity::getId, Function.identity()));
        for (OrderItemEntity orderItem : orderItemEntityList) {
            ItemEntity itemEntity = itemMap.get(orderItem.getItemId());
            Assert.notNull(itemEntity, orderItem.getItemId() + "对应商品不存在");
            Assert.isTrue(Objects.equals(orderItem.getItemPrice(), itemEntity.getSalePrice()), "商品单价不一致，商品id: " + orderItem.getItemId());
        }
    }
}